package cn.ly.core.proxy.cglib;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;  
import net.sf.cglib.proxy.MethodInterceptor;  
import net.sf.cglib.proxy.MethodProxy;  
  
/** 
 * 使用cglib动态代理 
 *  
 * @author student 
 *  
 */  
public class BookFacadeCglib implements MethodInterceptor {  
    private Object target;  
  
    /** 
     * 创建代理对象 
     *  
     * @param target 
     * @return
     * cglib 使用的是反射方式创建代理类proxy 
     */  
    public Object getInstance(Object target) {  
        this.target = target;  
        Enhancer enhancer = new Enhancer();  
        enhancer.setSuperclass(this.target.getClass());  
        // 给回调方法 使用
        enhancer.setCallback(this);  
        // 创建代理对象  
        return enhancer.create();  
    }  
  
    @Override  
    // 回调方法  
    public Object intercept(Object obj, Method method, Object[] args,  
            MethodProxy proxy) throws Throwable {
        Field field = obj.getClass().getField("sid");
        System.out.println("事务开始");
        int i = 0;
        for(Object arg : args){
            if(arg instanceof String){
                arg = "[" + arg + "]";
            }else if(arg instanceof Integer){
                arg = ((Integer) arg).intValue() - 10;

            }
            args[i++] = arg;
        }
        proxy.invokeSuper(obj, args);  
        System.out.println("事务结束");  
        return null;  
    }  
    
    
    public static void main(String[] args) {  
        BookFacadeCglib cglib=new BookFacadeCglib();  
        BookFacadeImpl1 bookCglib = (BookFacadeImpl1)cglib.getInstance(new BookFacadeImpl1());  
        bookCglib.addBook("Lucy",25);
    }  
  
}  